package org.x.yuenovel.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.x.yuenovel.controller.dto.ResultDTO;
import org.x.yuenovel.enums.ResultCodeEnum;
import org.x.yuenovel.exception.ApiException;

/**
 * @author xuezhendong
 * @date 2022/4/21 11:03 下午
 */
@RestControllerAdvice
public class NovelExceptionHandler {

    private static Logger logger = LoggerFactory.getLogger(NovelExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    protected ResultDTO<String> handleException(Exception e) {
        if (e instanceof BindException) {
            String message = message(((BindException) e).getBindingResult());
            return ResultDTO.error("10001", message);
        }else if(e instanceof ApiException){
            return ResultDTO.error(((ApiException) e).getErrorCode(), e.getMessage());
        }else {//拦截总异常
            logger.error("系统异常:" + e.getMessage(), e);
            return ResultDTO.error(ResultCodeEnum.ERROR);
        }
    }

    private String message(BindingResult result) {
        if (result == null) {
            return "参数错误";
        }
        StringBuilder sb = new StringBuilder();
        result.getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            sb.append(fieldName).append(errorMessage).append(". ");
        });
        return sb.toString();
    }
}
